package com.hz.friends.activity;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.impl.AvalonLogger;

import android.R.integer;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.CalendarContract.Instances;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.global.Global;
import com.hz.friends.location.LocationService;
import com.hz.friends.serverrequest.ALEngineConfig.ALSexualOrientation;
import com.hz.friends.serverrequest.ALEngineConfig.ALUserGender;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.sound.SoundMeter;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

/**
 * 编辑用户资料 完善用户资料，注册成功后跳转，资料填写有必选项 2014/9/9
 * 
 * @author john
 * 
 */
public class EditUserInfosActivity extends SelectPhotoActivity implements
		OnClickListener {
	private int pageflag = 0;// 1: 完善用户资料 0:编辑用户资料
	private Button btn_pre;// 提交按钮
	private LinearLayout layoutheard1;// 顶部图片第一排
	private LinearLayout layoutheard2; // 顶部图片第二排
	private TextView txv_constellat; // 星座
	private TextView txv_introduction;// 介绍
	private TextView txv_name;// 昵称
	private final int INPUT_REQUEST = 11; // 输入页面跳转request
	private final int Language_REQUEST = 12; // 语言选择页面跳转request
	private TextView txv_birthday;// 生日
	private ImageView imv_heard;// 头像
	private TextView txv_language;// 语言
	private RadioGroup ragp_gender;// 性别RadioGroup
	private RadioGroup ragp_sexlike;// 性取向RadioGroup
	private TextView txv_location; // 位置
	private AVUser user = null; // 当前页面用户
	private AQuery aq;// 图片加载对象
	private LinearLayout include_menu;
	private Animation slidebotomein;
	private Animation slidebotomeout;
	private TextView txv_refrest;
	private Button btn_speak;
	private ImageView imv_speakanim;
	private TextView txv_speakduration;
	private SoundMeter mSensor;
	private ImageView imv_location;
	private ProgressBar prob_location;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edituserinfos);
		init();
		initViews();
		initEvents();
		addTopImages();
		setViews();
	}

	@Override
	protected void init() {
		this.pageflag = getIntent().getIntExtra("pageflag", 0); // 1: 完善用户资料
																// 0:编辑用户资料
		user = ((CustomApplication) getApplication()).user;
		aq = new AQuery(this); // 图片加载对象
		slidebotomein = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slide_botome_in); // 从底部进动画
		slidebotomeout = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.slide_botome_out); // 从底部出动画
		mSensor = new SoundMeter();

	}

	@Override
	protected void initViews() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left); // bar
		imbtn_bar_left.setOnClickListener(this);
		imbtn_bar_left.setVisibility(View.VISIBLE); // 左边按钮
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right); // bar
																						// 右边按钮
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title); // bar
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		// 标题

		layoutheard1 = (LinearLayout) findViewById(R.id.layoutheard1); // 图片展示第一排
		layoutheard2 = (LinearLayout) findViewById(R.id.layoutheard2);// 图片展示第二排
		LinearLayout layout_heard = (LinearLayout) findViewById(R.id.layout_heard); // 头像布局
		imv_heard = (ImageView) findViewById(R.id.imv_heard);// 头像
		LinearLayout layout_name = (LinearLayout) findViewById(R.id.layout_name);// 昵称布局
		txv_name = (TextView) findViewById(R.id.txv_name);// 昵称
		ragp_gender = (RadioGroup) findViewById(R.id.ragp_gender);// 性别RadioGroup
		LinearLayout layout_location = (LinearLayout) findViewById(R.id.layout_location);// 位置
		txv_location = (TextView) findViewById(R.id.txv_location);// 位置
		imv_location = (ImageView) findViewById(R.id.imv_location);// 位置动画按钮
		prob_location = (ProgressBar) findViewById(R.id.prob_location);// 位置动画按钮
		LinearLayout layout_introduction = (LinearLayout) findViewById(R.id.layout_introduction);// 介绍信息布局
		txv_introduction = (TextView) findViewById(R.id.txv_introduction);// 介绍信息
		btn_speak = (Button) findViewById(R.id.btn_speak);// 按住说话
		imv_speakanim = (ImageView) findViewById(R.id.imv_speakanim);// 按住说话录音动画
		txv_speakduration = (TextView) findViewById(R.id.txv_speakduration);// 按住说话录音时长
		LinearLayout layout_birthday = (LinearLayout) findViewById(R.id.layout_birthday); // 生日布局
		txv_birthday = (TextView) findViewById(R.id.txv_birthday); // 生日
		LinearLayout layout_constellat = (LinearLayout) findViewById(R.id.layout_constellat);// 星座布局
		txv_constellat = (TextView) findViewById(R.id.txv_constellat);// 星座
		ragp_sexlike = (RadioGroup) findViewById(R.id.ragp_sexlike);// 性取向RadioGroup
		LinearLayout layout_language = (LinearLayout) findViewById(R.id.layout_language); // 语言布局
		txv_language = (TextView) findViewById(R.id.txv_language);// 语言
		btn_pre = (Button) findViewById(R.id.btn_pre); // 提交按钮
		include_menu = (LinearLayout) findViewById(R.id.include_menu); // 菜单布局
		TextView option1 = (TextView) include_menu.findViewById(R.id.option1); // option1
		TextView option2 = (TextView) include_menu.findViewById(R.id.option2); // option2
		TextView option3 = (TextView) include_menu.findViewById(R.id.option3); // option3

		// 完善资料相关 用于标识必填 *标识图标
		ImageView imv_namestart = (ImageView) findViewById(R.id.imv_namestart); // 昵称必填标识
		ImageView imv_genderstart = (ImageView) findViewById(R.id.imv_genderstart); // 性别必填标识
		ImageView imv_locationstart = (ImageView) findViewById(R.id.imv_locationstart); // 位置必填标识
		ImageView imv_languagestart = (ImageView) findViewById(R.id.imv_languagestart); // 语言必填标识
		ImageView imv_introductionstart = (ImageView) findViewById(R.id.imv_introductionstart); // 介绍不必填
		LinearLayout layout_completips = (LinearLayout) findViewById(R.id.layout_completips);// *标识说明布局
		// 编辑资料相关
		FrameLayout layout_topimages = (FrameLayout) findViewById(R.id.layout_topimages);// 顶部图片区域
		View view_edit = (View) findViewById(R.id.view_edit); // 头像布局下方填充view
		// 监听
		layout_name.setOnClickListener(this);
		layout_introduction.setOnClickListener(this);
		layout_constellat.setOnClickListener(this);
		layout_heard.setOnClickListener(this);
		layout_language.setOnClickListener(this);
		layout_birthday.setOnClickListener(this);
		include_menu.setOnClickListener(this);
		option1.setOnClickListener(this);
		option2.setOnClickListener(this);
		option3.setOnClickListener(this);
		layout_location.setOnClickListener(this);
		imv_location.setOnClickListener(this);

		// 初始化相关页面
		if (pageflag == 1) { // 完善用户资料
			imbtn_bar_left.setVisibility(View.INVISIBLE);
			imbtn_bar_right.setVisibility(View.INVISIBLE);
			imbtn_bar_title.setText("Perfect information");
			view_edit.setVisibility(View.GONE);
			layout_topimages.setVisibility(View.GONE);
			btn_pre.setText("Registration successful");
		} else {// 编辑用户资料
			imbtn_bar_right.setVisibility(View.INVISIBLE);
			imbtn_bar_title.setText("Edit data");
			imv_languagestart.setVisibility(View.GONE);
			imv_locationstart.setVisibility(View.GONE);
			imv_genderstart.setVisibility(View.GONE);
			imv_namestart.setVisibility(View.GONE);
			layout_completips.setVisibility(View.GONE);
			imv_introductionstart.setVisibility(View.GONE);
		}

	}

	@Override
	protected void initEvents() {
		// 性别
		ragp_gender.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == R.id.radbt_female) { // 女性0
					ragp_gender.setTag(0);
				} else { // 男性1
					ragp_gender.setTag(1);
				}
			}
		});
		// 性取向
		ragp_sexlike.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == R.id.rabtn01) {
					ragp_sexlike.setTag(0);
				} else if (checkedId == R.id.rabtn02) {
					ragp_sexlike.setTag(1);
				} else {
					ragp_sexlike.setTag(2);
				}
			}
		});

		btn_speak.setOnTouchListener(new PressToSpeakListen());

	}

	@Override
	protected void setViews() {
		// 个人信息
		String heardurl = user.getString("headViewURL");
		String nickname = user.getString("nickname");
		String signature = user.getString("signature");
		int gender = user.getInt("gender");
		int sexualOrientation = user.getInt("sexualOrientation");
		Date brithday = user.getDate("brithday");
		String place = user.getString("place");

		txv_name.setText(nickname);
		txv_introduction.setText(signature);
		txv_location.setText(place);
		setBirthday(brithday);
		if (gender == ALUserGender.ALUserGenderOfFemale.get_value()) {// 女性
			((RadioButton) ragp_gender.getChildAt(0)).setChecked(true);
			ragp_gender.setTag(0);
		} else {// 男性
			((RadioButton) ragp_gender.getChildAt(1)).setChecked(true);
			ragp_gender.setTag(1);
		}

		// 性取向
		if (sexualOrientation == ALSexualOrientation.ALSexualOrientationOfHomosexual
				.get_value()) {
			((RadioButton) ragp_sexlike.getChildAt(0)).setChecked(true);
			ragp_sexlike.setTag(0);
		} else if (sexualOrientation == ALSexualOrientation.ALSexualOrientationOfHeterosexual
				.get_value()) {
			((RadioButton) ragp_sexlike.getChildAt(1)).setChecked(true);
			ragp_sexlike.setTag(1);
		} else if (sexualOrientation == ALSexualOrientation.ALSexualOrientationOfBisexuality
				.get_value()) {
			((RadioButton) ragp_sexlike.getChildAt(2)).setChecked(true);
			ragp_sexlike.setTag(2);
		}

		// 默认头像
		final int width = DensityUtil.dip2px(this, 70);
		final int stroke = DensityUtil.dip2px(this, 1);
		Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
		Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(this,
				crclebitmap, width, stroke, "#eeeeee");
		imv_heard.setImageBitmap(crclestrokebitmap);
		// 头像
		aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
			@Override
			public void callback(String url, Bitmap bitmap, AjaxStatus status) {
				Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
						EditUserInfosActivity.this, bitmap, width, stroke,
						"#eeeeee");
				imv_heard.setImageBitmap(mbitmap);
			}
		});

		// 获取图片
		ALUserEngine.defauleEngine().getUserAlbum(user, 8, new CallBack() {

			@Override
			public void done(Object object, AVException avexception) {
				MLog.i(TAG, "getUserAlbum  object：" + object + "  avexception:"
						+ avexception);
				if (avexception == null) {
					if (object != null && object instanceof List) {
						picpaths.addAll((List<AVObject>) object);
						addTopImages();
					}
				} else {
					avexception.printStackTrace();
				}
			}
		});
	}

	/**
	 * 设置生日
	 * 
	 * @param birthday
	 */
	private void setBirthday(Date birthday) {
		if (birthday == null)
			birthday = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		txv_birthday.setText(sdf.format(birthday));
		String[] strs = sdf.format(birthday).split("-");
		String constell = UtilTools.getConstellation(Integer.parseInt(strs[1]),
				Integer.parseInt(strs[2]));
		txv_constellat.setText(constell);
	}

	private List picpaths = new ArrayList(); // 顶部图片数据源
	private List<AVObject> delepiclist = new ArrayList<AVObject>(); // 顶部图片数据源

	/**
	 * 添加顶部图片
	 */
	private void addTopImages() {
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int mScreenWidth = metric.widthPixels;
		int offset = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 11 * 2 + 6 * 3, getResources()
						.getDisplayMetrics());
		final int rightmargin = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int radius = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 6, getResources()
						.getDisplayMetrics());
		final int width = (mScreenWidth - offset) / 4;

		layoutheard1.removeAllViews();
		layoutheard2.removeAllViews();
		// 添加图片
		for (int i = 0; i < picpaths.size(); i++) {
			Object picpath = picpaths.get(i);
			final ImageView mImageView = new ImageView(
					EditUserInfosActivity.this);
			mImageView.setTag(picpath);
			mImageView.setScaleType(ScaleType.FIT_XY);
			if (picpath instanceof String) {// 刚添加的
				Bitmap bitmap = BitmapUtils.createRoundConerImage(
						BitmapFactory.decodeFile((String) picpath), width,
						radius);
				mImageView.setImageBitmap(bitmap);
			}
			if (picpath instanceof AVObject) {// 网络上的
				String url = ((AVObject) picpath).getString("url");
				// aq.id(mImageView).image(url, true, true);
				aq.id(mImageView).image(url, true, true, 0, 0,
						new BitmapAjaxCallback() {
							protected void callback(String url, ImageView iv,
									Bitmap bm, AjaxStatus status) {
								if (bm != null) {
									Bitmap bitmap = BitmapUtils
											.createRoundConerImage(bm, width,
													radius);
									iv.setImageBitmap(bitmap);
									iv.setBackgroundColor(Color.TRANSPARENT);
								}
							};
						});

			}

			LinearLayout.LayoutParams lap = new LinearLayout.LayoutParams(
					width, width);
			if (i != 4)
				lap.rightMargin = rightmargin;
			mImageView.setLayoutParams(lap);
			if (i < 4) {
				layoutheard1.addView(mImageView);
			} else {
				layoutheard2.addView(mImageView);
			}
			final int postion = i;
			mImageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					include_menu.startAnimation(slidebotomein);
					include_menu.setVisibility(View.VISIBLE);
					include_menu.setTag(postion);
				}
			});

		}

		// 添加按钮
		final ImageView addImageView = new ImageView(this);
		addImageView.setImageResource(R.drawable.userinfo_addimage);
		addImageView.setScaleType(ScaleType.FIT_CENTER);
		LinearLayout.LayoutParams lap = new LinearLayout.LayoutParams(width,
				width);
		addImageView.setLayoutParams(lap);
		addImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setIssmallpic(false);
				getPhoto("图片");
				setMcallback(new Callback() {
					@Override
					public void dosomething() {
						File file = getLargepic_file();
						if (file == null)
							return;
						picpaths.add(file.getAbsolutePath());
						addTopImages();
					}
				});
			}
		});

		if (picpaths.size() < 4)
			layoutheard1.addView(addImageView);
		else if (picpaths.size() < 8)
			layoutheard2.addView(addImageView);

	}

	private long startVoiceT;
	private long endVoiceT;
	/**
	 * 按住说话listener
	 * 
	 */
	class PressToSpeakListen implements View.OnTouchListener {

	
		private String voiceName;
		

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (!Environment.getExternalStorageDirectory().exists()) {
					Toast.makeText(getApplicationContext(), "No SDCard",
							Toast.LENGTH_SHORT).show();
					return false;
				}
				v.setPressed(true);
				startVoiceT = System.currentTimeMillis();
				voiceName = startVoiceT + ".amr";
				startRecord(voiceName);
				return true;
			case MotionEvent.ACTION_MOVE:
				return true;
			case MotionEvent.ACTION_UP:
				stopRecord();
				v.setPressed(false);
				// endVoiceT = SystemClock.currentThreadTimeMillis();
				endVoiceT = System.currentTimeMillis();
				int time = (int) ((endVoiceT - startVoiceT) / 1000.0);
				if (time < 1) {
					Toast.makeText(getApplicationContext(), "录音时间必须大于1s",
							Toast.LENGTH_SHORT).show();
					mSensor.setName(null);
				} else {
					String voicepath = mSensor.getVoiceDir() + voiceName;
					btn_speak.setTag(voicepath);
					mSensor.setVoiceduration(time);
				}
				return true;
			default:
				return false;
			}
		}

	}

	// 开始录音
	private void startRecord(String name) {
		synchronized (mSensor) {
			MLog.i(TAG, "---startRecord-name:" + name);
			mSensor.start(name);
			imv_speakanim.setVisibility(View.VISIBLE);
			final AnimationDrawable voiceAnimation = (AnimationDrawable) imv_speakanim
					.getDrawable();
			voiceAnimation.start();
			txv_speakduration.setText(60 + "\'\'");
			txv_speakduration.setTag(60);
			mhandler.sendEmptyMessageDelayed(2, 1000);

		}

	}

	// 停止录音
	private void stopRecord() {
		synchronized (mSensor) {
			MLog.i(TAG, "---stopRecord--s");
			// mHandler.removeCallbacks(mSleepTask);
			mSensor.stop();
			final AnimationDrawable voiceAnimation = (AnimationDrawable) imv_speakanim
					.getDrawable();
			voiceAnimation.stop();
			imv_speakanim.setVisibility(View.INVISIBLE);
			btn_speak.setTag(mSensor.getVoicePath());
			mhandler.removeMessages(2);
			int time = (int) ((endVoiceT - startVoiceT) / 1000.0);
			mSensor.setVoiceduration(time);
			
			int duration = 60;
			try {
				duration = (Integer) txv_speakduration.getTag();
			} catch (Exception e) {
			}
			duration = 60 - duration;
			txv_speakduration.setText(String.valueOf(duration) + "\'\'");

		}

	}

	private TextView inputTextView = null; // 输入textview

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imbtn_bar_left:// 顶部左侧
			finish();
			break;
		case R.id.layout_name: // 昵称
			Intent nameintent = new Intent(this, InfosInputActivty.class);
			nameintent.putExtra("TitleMessage", "Name");
			nameintent.putExtra("text", txv_name.getText().toString());
			nameintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(nameintent, INPUT_REQUEST);
			inputTextView = txv_name;
			break;
		case R.id.layout_introduction: // 介绍
			Intent introdintent = new Intent(this, InfosInputActivty.class);
			introdintent.putExtra("TitleMessage", "Introduction");
			introdintent
					.putExtra("text", txv_introduction.getText().toString());
			introdintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(introdintent, INPUT_REQUEST);
			inputTextView = txv_introduction;
			break;
		case R.id.layout_constellat:// 星座
			Intent constellintent = new Intent(this, InfosInputActivty.class);
			constellintent.putExtra("TitleMessage", "Constellation");
			constellintent
					.putExtra("text", txv_constellat.getText().toString());
			constellintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(constellintent, INPUT_REQUEST);
			inputTextView = txv_constellat;
			break;
		case R.id.layout_birthday: // 生日
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date birthday = sdf.parse(txv_birthday.getText().toString());
				Calendar cal = Calendar.getInstance();
				cal.setTime(birthday);
				int year = cal.get(Calendar.YEAR);
				int month = cal.get(Calendar.MONTH);
				int day = cal.get(Calendar.DAY_OF_MONTH);
				showDateDialog(year, month, day);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			break;
		case R.id.layout_heard: // 头像
			getPhoto("头像");
			setIssmallpic(true);
			final int size = DensityUtil.dip2px(this, 70);
			final int stroke = DensityUtil.dip2px(this, 2);
			setSize(size);
			setMcallback(new Callback() {
				@Override
				public void dosomething() {
					File file = getSmallpic_file();
					if (file == null)
						return;
					Bitmap bitmap = BitmapFactory.decodeFile(file
							.getAbsolutePath());
					Bitmap mbtimap = BitmapUtils.getCircleStrokbitmap(
							EditUserInfosActivity.this, bitmap, size, stroke,
							"#c4c4c5");
					imv_heard.setImageBitmap(mbtimap);
					imv_heard.setTag(file.getAbsolutePath());
					bitmap.recycle();
				}
			});
			break;
		case R.id.layout_language: // 语言
			Intent languageintent = new Intent(this,
					SelectLanguageActivity.class);
			languageintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(languageintent, Language_REQUEST);
			inputTextView = txv_language;
			break;
		case R.id.include_menu:// menu界面
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			break;
		case R.id.option1:// 查看
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			Object tag = include_menu.getTag();
			if (tag != null && tag instanceof Integer) {
				Intent largeintent = new Intent(this, BigImageActivity.class);

				int index = (Integer) tag;
				Object path = picpaths.get(index);
				if (path instanceof String) {
					largeintent.putExtra("imagePath", (String) path);
				}
				if (path instanceof AVObject) {
					largeintent.putExtra("imageUrl",
							((AVObject) path).getString("url"));
				}
				startActivity(largeintent);
			}
			break;
		case R.id.option2:// 删除
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			Object deletetag = include_menu.getTag();
			if (deletetag != null && deletetag instanceof Integer) {
				int index = (Integer) deletetag;
				if (picpaths.get(index) instanceof AVObject) { // 保存需删除的网络图片
					delepiclist.add((AVObject) picpaths.get(index));
				}
				picpaths.remove(index);
				addTopImages();
			}
			break;
		case R.id.option3:// 取消
			include_menu.startAnimation(slidebotomeout);
			include_menu.setVisibility(View.GONE);
			break;
		case R.id.imv_location://定位
//			 Matrix matrix = new Matrix(); 
//			 Bitmap  bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.edituserinfo_cycle)).getBitmap();  
//	          //设置图像的旋转角度    
//	          matrix.setRotate(0);
//	          //旋转图像，并生成新的Bitmap对像  
//	          bitmap=Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//	          //重新在ImageView组件中显示旋转后的图像  
//	          imv_location.setImageBitmap(bitmap); 
			break;
		case R.id.layout_location://定位
			Intent locationintent = new Intent(this, LocationService.class);
			if(prob_location.getTag() == null){//开始
	             startService(locationintent);
	             prob_location.setVisibility(View.VISIBLE);
	             prob_location.setTag("1");
	             //超时处理
	             mhandler.removeMessages(3);
	             mhandler.sendEmptyMessageDelayed(3, 1000*100);
			}else{//停止
				stopService(locationintent);
				 prob_location.setVisibility(View.INVISIBLE);
	             prob_location.setTag(null);
			}
			

			break;
		default:
			break;
		}
	}

	/**
	 * 日期选择对话框
	 * 
	 * @param year
	 * @param moth
	 * @param day
	 */
	private void showDateDialog(final int year, final int moth, final int day) {
		new DatePickerDialog(this, new OnDateSetListener() {
			
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				Calendar nowcal = Calendar.getInstance();
				Calendar selectcal = Calendar.getInstance();
				selectcal.set(year, monthOfYear, dayOfMonth);
				if(selectcal.after(nowcal)){
					showToast("日期必须小于当前日期");
					return;
				}
				
				try {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date birthday = sdf.parse(year + "-" + (monthOfYear + 1)
							+ "-" + dayOfMonth);
					setBirthday(birthday);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}, year, moth, day).show();
	}

	/**
	 * 提交编辑信息
	 * 
	 * @param view
	 */
	public void onSubmit(View view) {
		waitcount = 0;
		String heardFilePath = (String) imv_heard.getTag(); // 头像文件路径
		String name = txv_name.getText().toString(); // 昵称
		int gender = -1; // 性别
		if (ragp_gender.getTag() != null)
			gender = (Integer) ragp_gender.getTag();
		String location = txv_location.getText().toString().trim(); // 位置
		String brithday = txv_birthday.getText().toString().trim(); // 生日
		String conStellation = txv_constellat.getText().toString().trim(); // 星座
		String introduction = txv_introduction.getText().toString().trim(); // 个人介绍
		int sexual = -1; // 性取向
		if (ragp_sexlike.getTag() != null)
			sexual = (Integer) ragp_sexlike.getTag();
		String language = txv_language.getText().toString(); // 语言

		if (pageflag == 1) { // 完善资料有必填约束
			if (TextUtils.isEmpty(name)) {
				showToast("Name为必填项");
				return;
			}
			if (gender == -1) {
				showToast("请选择性别");
				return;
			}
			if (TextUtils.isEmpty(location)) {
				showToast("location为必填项");
				return;
			}
			if (TextUtils.isEmpty(language) || language.contains("Choose")) {
				showToast("请选择语言");
				return;
			}
		}
		ALUserGender enumgender = null;
		if (gender == 0) {
			enumgender = ALUserGender.ALUserGenderOfFemale;
		} else if (gender == 1) {
			enumgender = ALUserGender.ALUserGenderOfMale;
		}

		Date datebirthday = null;
		try {
			SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
			datebirthday = spf.parse(brithday);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		ALSexualOrientation sexualorientation = null;
		if (sexual == 0) {
			sexualorientation = ALSexualOrientation.ALSexualOrientationOfHomosexual;
		} else if (sexual == 1) {
			sexualorientation = ALSexualOrientation.ALSexualOrientationOfHeterosexual;
		} else if (sexual == 2) {
			sexualorientation = ALSexualOrientation.ALSexualOrientationOfBisexuality;
		}

//		uploadInfo(name, enumgender, sexualorientation, introduction,
//				datebirthday, null, (String) imv_heard.getTag(),null,0d);
		createWiatDialog("正在上传资料");
		uploadVoice(name, enumgender, sexualorientation, introduction,
		datebirthday, null, (String) imv_heard.getTag(),null,0d);
		uploadpics();
		deletePics();
	}

	//上传语音
	private void uploadVoice(final String name, final ALUserGender enumgender,
			final ALSexualOrientation sexualorientation,
			final String introduction, final Date datebirthday,
			String heardurl, String heardfilepath,String voiceurl,double voiceduration){
		
			if(mSensor.getName() == null){//不需要上传语音
				uploadInfo(name, enumgender, sexualorientation, introduction,
						datebirthday, null, (String) imv_heard.getTag(),null,0);
			}else{//上传语音
				try {
					final AVFile file = AVFile.withAbsoluteLocalPath(mSensor.getName(),mSensor.getVoicePath());
					file.saveInBackground(new SaveCallback() {
						@Override
						public void done(AVException arg0) {
							if(file.getUrl() == null){
								Message msg = mhandler.obtainMessage(1, "编辑资料失败");
								mhandler.sendMessage(msg);
							}else{
								uploadInfo(name, enumgender, sexualorientation, introduction,
										datebirthday, null, (String) imv_heard.getTag(),file.getUrl(),mSensor.getVoiceduration());
							}
						}
						
					});
				} catch (Exception e) {
				  e.printStackTrace();
					Message msg = mhandler.obtainMessage(1, "编辑资料失败");
					mhandler.sendMessage(msg);
 				}
					
			}
				 
	}

	/**
	 * 上传用户信息
	 * 
	 * @param name
	 * @param enumgender
	 * @param introduction
	 * @param sexual
	 * @param datebirthday
	 */
	private void uploadInfo(final String name, final ALUserGender enumgender,
			final ALSexualOrientation sexualorientation,
			final String introduction, final Date datebirthday,
			String heardurl, String heardfilepath, final String voiceurl,final double voicedurtion) {
		if (waitcount > 3)
			return;
		if (heardfilepath != null) {
			try {
				final AVFile file = AVFile.withAbsoluteLocalPath(
						System.currentTimeMillis() + ".jpg",
						(String) imv_heard.getTag());
				file.saveInBackground(new SaveCallback() {

					@Override
					public void done(AVException arg0) {
						if (file.getUrl() == null) {
							// cancleWaitDialog();
							Message msg = mhandler.obtainMessage(1, "编辑资料失败");
							mhandler.sendMessage(msg);
							// showToast("上传失败");
							return;
						} else {
							uploadInfo(name, enumgender, sexualorientation,
									introduction, datebirthday, file.getUrl(),
									null,voiceurl,voicedurtion);
						}
					}
				});
			} catch (Exception e) {
				Message msg = mhandler.obtainMessage(1, "编辑资料失败");
				mhandler.sendMessage(msg);
				e.printStackTrace();
			}
			return;
		}

		ALUserEngine.defauleEngine().updateUserInfo(name, null, enumgender,
				heardurl, sexualorientation, voiceurl, voicedurtion, introduction, null,
				null, datebirthday, null, null, null, null, null, null, null,
				null, null, null, new CallBack() {
					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "updateUserInfo object:" + object
								+ " avexception:" + avexception);
						// cancleWaitDialog();
						String txt;
						if (avexception == null) {
							// showToast("编辑资料成功");
							txt = "编辑资料成功";
							// if (pageflag == 1)
							// startActivity(MaintabsActivity.class);
							// finish();
						} else {
							// showToast("编辑资料失败");
							txt = "编辑资料失败";
							avexception.printStackTrace();
						}
						Message msg = mhandler.obtainMessage(1, txt);
						mhandler.sendMessage(msg);
					}
				});

	}

	int uploadpiccount = 0; // 统计图片上传
	int waitcount = 0; // 删除图片加1 上传图片加1 编辑资料加1 3取消waitdialog

	// 上传图片
	private void uploadpics() {
		final List<AVObject> uploadpics = new ArrayList<AVObject>();// 需要上传的图片
		final List<String> uploadpiclist = new ArrayList<String>();// 需要上传的图片

		// 过滤需要上传的图片
		for (int i = 0; i < picpaths.size(); i++) {
			Object obj = picpaths.get(i);
			if (obj instanceof String) {
				uploadpiclist.add((String) obj);
			}
		}

		// 上传
		for (int i = 0; i < uploadpiclist.size(); i++) {
			String filepath = uploadpiclist.get(i);
			try {
				final AVFile file = AVFile.withAbsoluteLocalPath(
						System.currentTimeMillis() + ".jpg", filepath);
				file.saveInBackground(new SaveCallback() {

					@Override
					public void done(AVException e) {
						if (e != null) {
							e.printStackTrace();
							uploadpiccount++;
							isuploadPics(uploadpiclist.size(), uploadpics);
						} else {// 上传文件成功
								// 创建photo
							ALUserEngine.defauleEngine().createPhoto(
									file.getUrl(), null, new CallBack() {

										@Override
										public void done(Object object,
												AVException avexception) {
											uploadpiccount++;
											if (avexception != null) {
												avexception.printStackTrace();
											} else {// 创建成功
												if (object != null
														&& object instanceof AVObject)
													uploadpics
															.add((AVObject) object);
											}
											isuploadPics(uploadpiclist.size(),
													uploadpics);

										}
									});
						}
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
				uploadpiccount++;
				isuploadPics(uploadpiclist.size(), uploadpics);
			}

		}
		if (uploadpiclist.size() == 0)
			isuploadPics(uploadpiclist.size(), uploadpics);

	}

	// 正式上传照片
	private void isuploadPics(int count, List<AVObject> photos) {
		if (uploadpiccount == count) {
			MLog.i(TAG, "上传照片数:" + count + " 实际上传数:" + photos.size());
			if (!photos.isEmpty()) {
				ALUserEngine.defauleEngine().updateMyAlbum(photos,
						new CallBack() {

							@Override
							public void done(Object object,
									AVException avexception) {
								if (avexception != null) {// 失败
									avexception.printStackTrace();
								} else {// 成功

								}
								mhandler.sendEmptyMessage(1);
							}
						});
			} else {
				mhandler.sendEmptyMessage(1);
			}

		}
	}

	// 删除网络图片
	private void deletePics() {
		MLog.i(TAG, "删除照片数:" + delepiclist.size());
		if (!delepiclist.isEmpty()) {
			ALUserEngine.defauleEngine().deleteMyAlbum(delepiclist,
					new CallBack() {

						@Override
						public void done(Object object, AVException avexception) {
							if (avexception != null) {// 失败
								avexception.printStackTrace();
							} else {// 成功

							}
							mhandler.sendEmptyMessage(1);
						}
					});
		} else {
			mhandler.sendEmptyMessage(1);
		}

	}

	private Handler mhandler = new Handler() {
		private String submitresult;

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1: // 处理信息提交结果
				waitcount++;
				if (msg.obj != null)
					submitresult = (String) msg.obj;
				if (waitcount == 3) {
					cancleWaitDialog();
					if (!TextUtils.isEmpty(submitresult)) {
						showToast(submitresult);
					}

					if ("编辑资料成功".equals(submitresult)) {
						if (pageflag == 1)
							startActivity(MaintabsActivity.class);
						finish();
					}

				}
				break;
			case 2:// 处理录音

				int duration = 60;
				try {
					duration = (Integer) txv_speakduration.getTag();
				} catch (Exception e) {
				}
				txv_speakduration.setTag(duration - 1);
				txv_speakduration
						.setText(String.valueOf(duration - 1) + "\'\'");
				this.sendEmptyMessageDelayed(2, 1000);

				if (duration - 1 == 0) { // 倒计时完成
					showToast("录音结束");
					stopRecord();
				}

				if (!btn_speak.isPressed() && mSensor.isRecording()) {// 如果在录音
																		// 但没有按压按钮
					stopRecord();
				}

				break;
			case 3://处理定位
				if(prob_location.getTag() != null){
					showToast("定位失败,请尝试重新定位");
					 Intent locationintent = new Intent(EditUserInfosActivity.this, LocationService.class);
					 stopService(locationintent);
					 prob_location.setVisibility(View.INVISIBLE);
		             prob_location.setTag(null);
				}
			     break;
			default:
				break;
			}

		};
	};
	private LocationReciverBroad mlocationReciverBroad;

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		// 完善用户资料
		if (pageflag == 1)
			startActivity(MaintabsActivity.class);
		this.finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)
			return;
		if (requestCode == INPUT_REQUEST || requestCode == Language_REQUEST) {// 输入\语言
			String text = data.getStringExtra("text");
			boolean ischange = data.getBooleanExtra("ischange", false);
			if (inputTextView != null && ischange)
				inputTextView.setText(text);
		}

	}
     @Override
    protected void onResume() {
     	super.onResume();
     	//生成广播处理   
     	mlocationReciverBroad = new LocationReciverBroad();   
     	//实例化过滤器并设置要过滤的广播   
     	IntentFilter intentFilter = new IntentFilter(Global.LOCAT_ACTION); 
     	//注册广播   
     	 registerReceiver(mlocationReciverBroad, intentFilter);  
    }
     
    @Override
    protected void onPause() {
    	super.onPause();
    	 Intent locationintent = new Intent(EditUserInfosActivity.this, LocationService.class);
		 stopService(locationintent);
    	unregisterReceiver(mlocationReciverBroad);
    }
	
    class LocationReciverBroad extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			MLog.i(TAG, "====reciver location brocats");
			double lat = intent.getDoubleExtra("lat", 0);
			double lon = intent.getDoubleExtra("lon", 0);
			String address = intent.getStringExtra("address");
			if("not_open_set".equals(address) && prob_location.getTag() != null){
				showToast("请打开Gps定位");
				 Intent locationintent = new Intent(EditUserInfosActivity.this, LocationService.class);
				 stopService(locationintent);
				 prob_location.setVisibility(View.INVISIBLE);
	             prob_location.setTag(null);
	             return;
			}
			
		   if(!TextUtils.isEmpty(address)&& prob_location.getTag() != null){
				showToast("定位成功");
				 Intent locationintent = new Intent(EditUserInfosActivity.this, LocationService.class);
				 stopService(locationintent);
				 prob_location.setVisibility(View.INVISIBLE);
	             prob_location.setTag(null);
	             txv_location.setText(address);
	             double[] intarr = new double[2];
	             intarr[0] = lat;
	             intarr[1] = lon;
	             txv_location.setTag(intarr);
	             
	             //上传经纬度
	             ALUserEngine.defauleEngine().updateLocation(lat, lon, address, new CallBack() {
					
					@Override
					public void done(Object object, AVException avexception) {
						// TODO Auto-generated method stub
						
					}
				});
	             return;
			
		   }	
		}
    	
    }

}
